package com.example.itcompanyinterview.container;

import java.util.List;

import com.example.itcompanyinterview.R;
import com.example.itcompanyinterview.object.Role;
import com.example.itcompanyinterview.object.RoleListViewCache;
import com.example.itcompanyinterview.tools.AsyncImageLoader;
import com.example.itcompanyinterview.tools.AsyncImageLoader.ImageCallback;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class MapListImageAndTextListAdapter extends ArrayAdapter<Role> {

	private ListView listView;
	private AsyncImageLoader asyncImageLoader;
	
	public MapListImageAndTextListAdapter(Activity activity, 
			List<Role> roleList, ListView listView) {
		super(activity, 0, roleList);
		this.listView = listView;
		asyncImageLoader = new AsyncImageLoader();
	}
	
    public View getView(int position, View convertView, ViewGroup parent) {
        Activity activity = (Activity) getContext();

        // Inflate the views from XML
        View rowView = convertView;
        RoleListViewCache viewCache;
        if (rowView == null) {
            LayoutInflater inflater = activity.getLayoutInflater();
            rowView = inflater.inflate(R.layout.role_item, null);
            viewCache = new RoleListViewCache(rowView);
            rowView.setTag(viewCache);
        } else {
            viewCache = (RoleListViewCache)rowView.getTag();
        }
        Role roleInfo = getItem(position);

        // Load the image and set it on the ImageView
        String imageUrl = roleInfo.getLogoUrl();
        ImageView imageView = viewCache.getRoleLogo();
        imageView.setTag(imageUrl);
        Drawable cachedImage = asyncImageLoader.loadDrawable(imageUrl, new ImageCallback() {
            public void imageLoaded(Drawable imageDrawable, String imageUrl) {
                ImageView imageViewByTag = (ImageView) listView.findViewWithTag(imageUrl);
                if (imageViewByTag != null) {
                    imageViewByTag.setImageDrawable(imageDrawable);
                }
            }
        });
        
        imageView.setImageDrawable(cachedImage);
        // Set the text on the TextView
		TextView roleTitle = viewCache.getRoleTitle();
		roleTitle.setText(roleInfo.getName());
        
        return rowView;
    }
	
}

